package org.example.Problem;

import java.util.*;


public class A {
    public int[] assignTasks(int[] servers, int[] tasks) {
        PriorityQueue<Pair> pp = new PriorityQueue<>();
        Map <Integer,Set<Pair> >mp = new HashMap<>();
        for (int i = 0;i<servers.length;i++) {
            pp.add(new Pair(servers[i],0,i));
        }
        int[] ans = new int[tasks.length];
        int time = 0;
        PriorityQueue<Integer> mi = new PriorityQueue<>();
        for(int i=0;i<tasks.length;i++){
            if(time<i) time = i;
            if(mp.get(time) != null){
                Set<Pair> st = mp.get(time);
                for(Pair x:st){
                    pp.add(x);
                }
            }
            Pair cur = pp.poll();
            if(cur == null){
                time = mi.poll();
                if(mp.get(time) != null){
                    Set<Pair> st = mp.get(time);
                    for(Pair x:st){
                        pp.add(x);
                    }
                }
                cur = pp.poll();
            }
            ans[i] = cur.name;
            cur.second = time + tasks[i];
            /*
            if(st[cur.second] == null){
                st[cur.second] = new HashSet<Pair>();
            }
            st[cur.second].add(cur);
            mi.add(cur.second);
            */
            if(mp.get(cur.second) == null){
                Set<Pair> st = new HashSet<>();
                mp.put(cur.second,st);
            }
            mp.get(cur.second).add(cur);
            mi.add(cur.second);
            while (mi.size()>0&&time>=mi.peek()) mi.poll();
            mp.put(time,null);
        }
        return ans;
    }
}
class Pair implements Comparable{
    int first,second,name;
    public Pair(int first, int second,int name) {
        this.first = first;
        this.second = second;
        this.name = name;
    }
    @Override
    public int compareTo(Object x) {
        Pair o = (Pair) x;
        if(o.first<this.first) return 1;
        else if(o.first == this.first && o.name<this.name) return 1;
        else return -1;
    }
}